package com.xcw.controller;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * @Author bhx
 * @Date 2022/8/27 21:31
 * @Description TODO
 */
@Slf4j
@Controller
public class  WxController extends BaseController{

    @Autowired
    WxMpMessageRouter wxMpMessageRouter;

    @ResponseBody
    @RequestMapping(value = "/wx/back")
    public String wxCallback(String signature, String timestamp, String nonce, String echostr) throws IOException {
        if (StrUtil.isNotBlank(echostr)) {
            log.info("正在配置回调接口 ------------{}", echostr);
            return echostr;
        }

        boolean checkSignature = wxMpService.checkSignature(timestamp, nonce, signature);
        if (!checkSignature) {
            log.error("签名不合法");
            return null;
        }

        WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(request.getInputStream());
        WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(wxMpXmlMessage);

        return outMessage == null ? "" : outMessage.toXml();
    }
}
